<?php 
ini_set('date.timezone','Asia/Shanghai');
require_once(__DIR__ . "/lib/WxPay.Api.php");
require_once(__DIR__ . "/wpay/WxPay.JsApiPay.php");
require_once(__DIR__ . "/lib/WxPay.Notify.php");

//For 商户付款(用户提现）
class Enpay {
    private $parameters = [];
    public function __construct() {
    }
 
    /*初始化数组参数*/
    public function setParameter($key,$value){
        $this->parameters[$key] = $value;
    }
    function formatBizQueryParaMap($paraMap, $urlencode){
        // var_dump($paraMap);//die;
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v){
            if($urlencode){
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar="";
        if (strlen($buff) > 0){
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        // var_dump($reqPar);
        return $reqPar;
    }

    /*  作用：生成签名 */
    function getSign($Obj){
        // var_dump($Obj);//die;
        $tmpparam =[];
        foreach ($Obj as $k => $v){
            $tmpparam[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($tmpparam);
        $String = $this->formatBizQueryParaMap($tmpparam, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY

        $String = $String."&key=".WxPayConfig::KEY;
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);

        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    /**
     * 将xml转为array
     * @param string $xml
     * @throws WxPayException
     */
    public function FromXml($xml)
    {   
        if(!$xml){
            throw new WxPayException("xml数据异常！");
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);        
        return $this->values;
    }
    /**
     * 将数组转换成xml
     */
    public function ToXml(){
        if(!is_array($this->parameters)|| count($this->parameters) <= 0){
            throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($this->parameters as $key=>$val){
            if (is_numeric($val)){
                    $xml.="<".$key.">".$val."</".$key.">";
            }else{
                    $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
       // log_message('info',"ToXml----");
       // log_message('info',$xml);
        return $xml; 
    }


     //微信提现,企业推荐
     public function en_pay($xml){
         return WxPayApi::en_pay($xml);
     }

    /*用户提现，企业付款*/
   
    public function en_pay_package($openid,$trade_no,$amount,$name,$desc){
        $this->setParameter('mch_appid',WxPayConfig::APPID);
        $this->setParameter('mchid',WxPayConfig::MCHID);
        $this->setParameter('nonce_str',$this->createNonceStr(16));
         // 用户openid
        $this->setParameter('openid', $openid);
        // 商户订单号
        $this->setParameter('partner_trade_no',$trade_no);
        // 校验用户姓名选项
        $this->setParameter('check_name', 'NO_CHECK');
        // 企业付款金额  单位为分
        $this->setParameter('amount', $amount*100);
        // 企业付款描述信息
        $this->setParameter('desc',$desc);
        // 调用接口的机器IP地址  自定义
        $this->setParameter('spbill_create_ip',$_SERVER["REMOTE_ADDR"]); 
        // 收款用户姓名
        $this->setParameter('re_user_name', $name);
        // 设备信息

        $sign=$this->getSign($this->parameters);
        $this->setParameter('sign', $sign);
        // var_dump($this->parameters);exit;
        $xml = $this->ToXml();
        if( !empty($xml) ) {
              return $xml ;
        }
        return  false;
    }
    
}
